package org.dromara.bykt.service.impl;

import org.dromara.bykt.domain.vo.BYKTCourseVo;
import org.dromara.bykt.domain.vo.BYKTSysUserVo;
import org.dromara.bykt.service.IBYKTCourseService;
import org.dromara.bykt.service.IBYKTSysUserService;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.dromara.bykt.domain.bo.BYKTCourseOrderBo;
import org.dromara.bykt.domain.vo.BYKTCourseOrderVo;
import org.dromara.bykt.domain.BYKTCourseOrder;
import org.dromara.bykt.mapper.BYKTCourseOrderMapper;
import org.dromara.bykt.service.IBYKTCourseOrderService;

import java.util.*;

/**
 * 课程订单Service业务层处理
 *
 * @author Hou
 * @date 2025-06-22
 */
@RequiredArgsConstructor
@Service
public class BYKTCourseOrderServiceImpl implements IBYKTCourseOrderService {

    private final BYKTCourseOrderMapper baseMapper;

    @Autowired
    private IBYKTSysUserService sysUserService;

    @Autowired
    private IBYKTCourseService courseService;

    /**
     * 查询课程订单
     *
     * @param id 主键
     * @return 课程订单
     */
    @Override
    public BYKTCourseOrderVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询课程订单列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 课程订单分页列表
     */
    @Override
    public TableDataInfo<BYKTCourseOrderVo> queryPageList(BYKTCourseOrderBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BYKTCourseOrder> lqw = buildQueryWrapper(bo);
        Page<BYKTCourseOrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(vo -> {
            BYKTSysUserVo byktSysUserVo = sysUserService.queryById(vo.getUserId());
            vo.setNickName(byktSysUserVo.getNickName());
            vo.setUserName(byktSysUserVo.getUserName());
            BYKTCourseVo byktCourseVo = courseService.queryById(vo.getCourseId());
            vo.setTitle(byktCourseVo.getTitle());
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的课程订单列表
     *
     * @param bo 查询条件
     * @return 课程订单列表
     */
    @Override
    public List<BYKTCourseOrderVo> queryList(BYKTCourseOrderBo bo) {
        LambdaQueryWrapper<BYKTCourseOrder> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BYKTCourseOrder> buildQueryWrapper(BYKTCourseOrderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BYKTCourseOrder> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(BYKTCourseOrder::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getOrderNo()), BYKTCourseOrder::getOrderNo, bo.getOrderNo());
        lqw.eq(bo.getUserId() != null, BYKTCourseOrder::getUserId, bo.getUserId());
        lqw.eq(bo.getCourseId() != null, BYKTCourseOrder::getCourseId, bo.getCourseId());
        lqw.eq(bo.getAmount() != null, BYKTCourseOrder::getAmount, bo.getAmount());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), BYKTCourseOrder::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getPayType()), BYKTCourseOrder::getPayType, bo.getPayType());
        lqw.eq(bo.getPayTime() != null, BYKTCourseOrder::getPayTime, bo.getPayTime());
        return lqw;
    }

    /**
     * 新增课程订单
     *
     * @param bo 课程订单
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(BYKTCourseOrderBo bo) {
        boolean flag = false;
        if (bo.getCourseIds() != null && !bo.getCourseIds().isEmpty()) {
            for (String courseIds : bo.getCourseIds().split(",")) {
                BYKTCourseOrder add = new BYKTCourseOrder();
                add.setUserId(bo.getUserId());
                add.setOrderNo(generateOrderNo());
                add.setCourseId(Long.valueOf(courseIds));
                add.setAmount(bo.getAmount());
                add.setStatus("1");
                add.setPayType(bo.getPayType());
                add.setPayTime(new Date());
                add.setCreateTime(new Date());
                validEntityBeforeSave(add);
                flag = baseMapper.insert(add) > 0;
                if (flag) {
                    bo.setId(add.getId());
                }
            }
        }
        return flag;
    }

    /**
     * 修改课程订单
     *
     * @param bo 课程订单
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BYKTCourseOrderBo bo) {
        BYKTCourseOrder update = MapstructUtils.convert(bo, BYKTCourseOrder.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BYKTCourseOrder entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除课程订单信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public Long queryCourseId(Long courseId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<BYKTCourseOrder>().eq(BYKTCourseOrder::getCourseId, courseId));
    }

    /**
     * 生成订单编号
     */
    private String generateOrderNo() {
        return "BYJY" + DateUtils.dateTimeNow() + org.apache.commons.lang3.StringUtils.leftPad(String.valueOf((int) (Math.random() * 10000)), 4, '0');
    }
}
